package com.ruoyi.system.controller;

import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.system.api.model.LoginUser;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.IErpGoodsWarehouseService;
import com.ruoyi.system.service.IErpSaleGoodsService;
import com.ruoyi.system.service.IErpSaleService;
import com.ruoyi.system.service.IErpSalesReturnService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.List;

import static com.ruoyi.common.security.utils.SecurityUtils.getLoginUser;

/**
 * 销售订单Controller
 *
 * @author 刘策
 * @date 2022-10-28
 */
@RestController
@RequestMapping("/sale")
public class ErpSaleController extends BaseController {
    @Autowired
    private IErpSaleService erpSaleService;

    @Autowired
    private IErpSaleGoodsService erpSaleGoodsService;

    @Autowired
    private IErpGoodsWarehouseService erpGoodsWarehouseService;

    @Autowired
    private IErpSalesReturnService erpSalesReturnService;

    /**
     * 查询销售订单列表
     */
    @RequiresPermissions("system:sale:list")
    @GetMapping("/list")
    public TableDataInfo list(ErpSale erpSale) {
        startPage();
        List<ErpSale> list = erpSaleService.selectErpSaleList(erpSale);
        return getDataTable(list);
    }

/*    *//**
     * 查询销售发货订单列表
     *//*
    @GetMapping("/deliveryList")
    public TableDataInfo deliveryList(ErpSale erpSale) {
        startPage();
        List<ErpSale> list = erpSaleService.selectErpSaleDeliveryList(erpSale);
        return getDataTable(list);
    }*/

    /**
     * 导出销售订单列表
     */
    @RequiresPermissions("system:sale:export")
    @Log(title = "销售订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ErpSale erpSale) {
        List<ErpSale> list = erpSaleService.selectErpSaleList(erpSale);
        ExcelUtil<ErpSale> util = new ExcelUtil<ErpSale>(ErpSale.class);
        util.exportExcel(response, list, "销售订单数据");
    }

    /**
     * 获取销售订单详细信息
     */
    @RequiresPermissions("system:sale:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(erpSaleService.selectErpSaleById(id));
    }

    /**
     * 新增销售订单
     */
    @RequiresPermissions("system:sale:add")
    @Log(title = "销售订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ErpSale erpSale) throws IllegalAccessException {
        List<SaleGoods> goodsList = erpSale.getGoodsList();
        for (SaleGoods saleGoods : goodsList) {
            if (saleGoods.getPrice() == null) {
                return AjaxResult.error("请填写销售单价");
            }
            if (saleGoods.getQuantity() == null) {
                return AjaxResult.error("请填写销售数量");
            }
            if (saleGoods.getOneGoodPrice() == null) {
                return AjaxResult.error("请填写表单数据");
            }
        }
        return toAjax(erpSaleService.insertErpSale(erpSale));
    }


    /**
     * 修改销售订单
     */
    @RequiresPermissions("system:sale:edit")
    @Log(title = "销售订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ErpSale erpSale) {
        List<SaleGoods> goodsList = erpSale.getGoodsList();
        for (SaleGoods saleGoods : goodsList) {
            if (saleGoods.getPrice() == null) {
                return AjaxResult.error("请填写销售单价");
            }
            if (saleGoods.getQuantity() == null) {
                return AjaxResult.error("请填写销售数量");
            }
        }
        return toAjax(erpSaleService.updateErpSale(erpSale));
    }

    /**
     * 删除销售订单
     */
    @RequiresPermissions("system:sale:remove")
    @Log(title = "销售订单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        for (Long id : ids) {
            erpSaleService.deleteErpSaleGoodBySaleId(id);
        }
        return toAjax(erpSaleService.deleteErpSaleByIds(ids));
    }

    /**
     * 删除订单关联商品方法
     */
    @DeleteMapping("/deleteGoods")
    public AjaxResult removeGoods(@RequestBody SaleGoods saleGoods) {
        return toAjax(erpSaleService.deleteErpSaleGoodById(saleGoods));
    }

    /**
     * 审核订单方法
     */
    @PutMapping("/updateType")
    public AjaxResult updateType(Long saleId, Long type, String num) {
        return toAjax(erpSaleService.updateErpSaleType(saleId, type, num));
    }

    /**
     * 确认发货前核对发货数量
     */
    @GetMapping("/ConfirmDeliveryQuantity")
    public AjaxResult ConfirmDeliveryQuantity(Long saleId) {
        List<ErpSaleGoodNum> erpSaleGoodNums = erpSaleService.selectGoodNumBySaleIdFromSale(saleId);
        List<ErpSaleGoodNum> erpSaleGoodNums1 = erpSaleService.selectGoodNumBySaleIdFromWarehouse(saleId);
        for (int i = 0; i < erpSaleGoodNums.size(); i++) {
            Long goodNum1 = erpSaleGoodNums.get(i).getGoodNum();
            Long goodNum = erpSaleGoodNums1.get(i).getGoodNum();
            if (goodNum != goodNum1) {
                Long goodId = erpSaleGoodNums.get(i).getGoodId();
                return AjaxResult.error("商品Id为" + goodId + "发货数量错误!");
            }
        }
        return AjaxResult.success();
    }

    /**
     * 添加销售仓库商品关联表
     */
    @PostMapping("/addGoodsSaleWarehouse")
    public AjaxResult addGoodsSaleWarehouse(@RequestBody List<ErpGoodsSaleWarehouse> erpGoodsSaleWarehouse) {
        Long saleNumber = 0L;
        Long saleId = null;
        Long goodId = null;
        for (ErpGoodsSaleWarehouse goodsSaleWarehouse : erpGoodsSaleWarehouse) {
            Long goodSaleWarehouse = goodsSaleWarehouse.getGoodSaleWarehouse();
            if (goodSaleWarehouse != 0L) {
                if (goodsSaleWarehouse.getGoodsNumber() < goodSaleWarehouse) {
                    return AjaxResult.error("库存不足!");
                }
                saleNumber = saleNumber + goodSaleWarehouse;
            }
            saleId = goodsSaleWarehouse.getSellId();
            goodId = goodsSaleWarehouse.getGoodId();
        }
        if (saleNumber == 0) {
            return AjaxResult.error("请填写商品数量!");
        }
        ErpSaleGoods erpSaleGoods = erpSaleGoodsService.selectErpSaleGoodsById(saleId, goodId);
        Long quantity = erpSaleGoods.getQuantity();
        if (saleNumber > quantity) {
            return AjaxResult.error("出库商品数目大于销售商品数量");
        }
        if (saleNumber < quantity) {
            return AjaxResult.error("出库商品数目与销售商品数量不同");
        }
        for (ErpGoodsSaleWarehouse goodsSaleWarehouse : erpGoodsSaleWarehouse) {
            if (goodsSaleWarehouse.getGoodSaleWarehouse() != 0L) {
                erpSaleService.addGoodsSaleWarehouse(goodsSaleWarehouse);
            }
        }
        return AjaxResult.success();
    }

    /**
     * 修改销售仓库商品关联表
     */
    @PostMapping("/upGoodsSaleWarehouse")
    public AjaxResult upGoodsSaleWarehouse(@RequestBody List<ErpGoodsSaleWarehouse> erpGoodsSaleWarehouse) {
        erpGoodsWarehouseService.deleteGoodNumberInfo(erpGoodsSaleWarehouse.get(0).getGoodId(), erpGoodsSaleWarehouse.get(0).getSellId());
        for (ErpGoodsSaleWarehouse goodsSaleWarehouse : erpGoodsSaleWarehouse) {
            if (goodsSaleWarehouse.getGoodSaleWarehouse() != 0L) {
                erpSaleService.addGoodsSaleWarehouse(goodsSaleWarehouse);
            }
        }
        return AjaxResult.success();
    }

    /**
     * 添加销售仓库商品关联表时校验接口
     */
    @PostMapping("/checkGoodsSaleWarehouse")
    public AjaxResult checkGoodsSaleWarehouse(@RequestBody List<ErpGoodsSaleWarehouse> erpGoodsSaleWarehouse) {
        Long saleNumber = 0L;
        Long saleId = null;
        Long goodId = null;
        for (ErpGoodsSaleWarehouse goodsSaleWarehouse : erpGoodsSaleWarehouse) {
            Long goodSaleWarehouse = goodsSaleWarehouse.getGoodSaleWarehouse();
            if (goodSaleWarehouse != 0L) {
                if (goodsSaleWarehouse.getGoodsNumber() < goodSaleWarehouse) {
                    return AjaxResult.error("库存不足!");
                }
                saleNumber = saleNumber + goodSaleWarehouse;
            }
            saleId = goodsSaleWarehouse.getSellId();
            goodId = goodsSaleWarehouse.getGoodId();
        }
        if (saleNumber == 0) {
            return AjaxResult.error("请填写商品数量!");
        }
        ErpSaleGoods erpSaleGoods = erpSaleGoodsService.selectErpSaleGoodsById(saleId, goodId);
        Long quantity = erpSaleGoods.getQuantity();
        if (saleNumber > quantity) {
            return AjaxResult.error("出库商品数目大于销售商品数量");
        }
        if (saleNumber < quantity) {
            return AjaxResult.error("出库商品数目与销售商品数量不同");
        }
        return AjaxResult.success();
    }


    /**
     * 退货商品接口
     */
    @PutMapping("/returnGoods")
    public AjaxResult returnGoods(@RequestBody List<ErpGoodsSaleWarehouse> erpGoodsSaleWarehouse) {
        Long saleId = null;
        BigDecimal returnAmount = new BigDecimal(0);
        for (ErpGoodsSaleWarehouse goodsSaleWarehouse : erpGoodsSaleWarehouse) {
            Long returnGoodNumber = goodsSaleWarehouse.getGoodReturnWarehouse();
            if (returnGoodNumber != 0L) {
                erpSaleService.returnGoods(goodsSaleWarehouse);
                returnAmount = goodsSaleWarehouse.getItemPricing().multiply(new BigDecimal(goodsSaleWarehouse.getGoodReturnWarehouse())).add(returnAmount);
            }
            saleId = goodsSaleWarehouse.getSellId();
        }
        ErpSale erpSale = erpSaleService.selectErpSaleById(saleId);
        if (erpSale.getReturnGoods() == 1) {
            ErpSalesReturn erpSalesReturn = new ErpSalesReturn();
            erpSalesReturn.setSaleId(erpSale.getId());
            erpSalesReturn.setReturnBonus(returnAmount);
            erpSalesReturn.setPaymentMethod(erpSale.getPaymentMethod());
            erpSalesReturn.setSaleOrderNum(erpSale.getSaleNumber());
            erpSalesReturn.setShipmentNum(erpSale.getShipmentNum());
            erpSalesReturn.setCustomerId(erpSale.getCustomerId());
            erpSalesReturn.setCustomerPhone(erpSale.getCustomerPhone());
            erpSalesReturn.setIsReturn(1L);
            LoginUser loginUser = getLoginUser();
            erpSalesReturn.setCreateUser(loginUser.getUsername());
            return toAjax(erpSalesReturnService.insertErpSalesReturn(erpSalesReturn));
        }
        if (erpSale.getReturnGoods() == 0) {
            return toAjax(erpSalesReturnService.updateSaleAmount(saleId, returnAmount));
        }
        return AjaxResult.error();
    }

}
